package com.qll123.module_aop.hook;

import android.text.TextUtils;

import com.qll123.module_aop.Reflect;
import com.qll123.module_aop.ReflectException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Aspect
public class AHookAspectInjector {
    @Pointcut("@within(com.qll123.module_aop.hook.AHook)||@annotation(com.qll123.module_aop.hook.AHook)")
    public void onHookMethod() {
    }

    @Around("execution(!synthetic * *(..)) && onHookMethod()")
    public void hookMethod(final ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        AHook hookMethod = method.getAnnotation(AHook.class);

        if (hookMethod==null) {
            return;
        }

        String beforeMethod = hookMethod.beforeMethod();
        String afterMethod = hookMethod.afterMethod();
        if (!TextUtils.isEmpty(beforeMethod)) {
            try {
                Reflect.on(joinPoint.getTarget()).call(beforeMethod);
            } catch (ReflectException e) {
                e.printStackTrace();
            }
        }
        joinPoint.proceed();

        if (!TextUtils.isEmpty(afterMethod)) {
            try {
                Reflect.on(joinPoint.getTarget()).call(afterMethod);
            } catch (ReflectException e) {
                e.printStackTrace();
            }
        }
    }
}
